<template>
	<view class="container">
		<view class="tab">
			<block v-for="(item,index) in tabNav" :key="index">
				<text :class="[current == index ? 'on' : '']" @click="current = index">{{item}}</text>
			</block>
		</view>
		<view>
			<view class="bd uni-list">
				<view class="uni-list-cell uni-list-cell-pd">
					<view class="uni-list-cell-left justify">手机号</view>
					<view class="uni-list-cell-db"><input type="number" class="uni-input" placeholder="请输入手机号"
							placeholder-style="color:#CACBCD" v-model="account" /></view>
					<button class="yzm" :disabled="disabled" @click="getCode" v-if="current == 0">{{ text }}</button>
				</view>
				<view class="uni-list-cell uni-list-cell-pd" v-if="current == 0">
					<view class="uni-list-cell-left">验证码</view>
					<view class="uni-list-cell-db"><input type="text" class="uni-input" placeholder="请输入短信验证码"
							placeholder-style="color:#CACBCD" v-model="captcha" /></view>
				</view>
				<view class="uni-list-cell uni-list-cell-pd" v-if="current == 1">
					<view class="uni-list-cell-left justify">密码</view>
					<view class="uni-list-cell-db"><input type="text" :password="isShow" class="uni-input"
							placeholder="请输入密码" placeholder-style="color:#CACBCD" v-model="password" /></view>
					<view class="jichu">
						<image class="collection" mode="widthFix" src="@/static/images/eye.png" v-if="showUpImg"
							@click="changePwd"></image>
						<image class="collection" mode="widthFix" src="@/static/images/eye_on.png" v-if="!showUpImg"
							@click="changePwd"></image>
					</view>
				</view>
				<view class="uni-list-cell uni-list-cell-pd" v-if="current == 1">
					<view class="uni-list-cell-db">
						<view class="uni-flex">
							<view class="uni-flex-item" @click="goUrl('')">忘记密码</view>
							<view @click="goUrl('')">找回密码</view>
						</view>
					</view>
				</view>
			</view>
			<view class="ft">
				<view class="p">
					<checkbox-group @change='isAgree=!isAgree'>
						<checkbox class="checkbox" value="cb" :checked="isAgree ? true : false" />
						<text class="vertical-middle">
							登录即视为同意<text class="text-green">《用户使用协议》、《隐私权条款》</text>
						</text>
					</checkbox-group>
				</view>
				<button type="primary" :class="['btn','text-white', keyLock ? 'bg-color' : 'bg-gray']"
					@click="loginMobile">登录</button>
			</view>
		</view>

		<u-modal :show="showAuthorizeUser" :show-confirm-button="false">
			<view class="slot-content">
				<div class="auth-card">
					<div class="img">
						<img class="avatar-img" src="../../../static/images/default_avatar.png" mode="widthFix">
					</div>
					<div class="title">车灯师平台</div>
					<div class="content">邀请您补全个人信息<br></br>（昵称、头像）</div>
					<div style="margin-left: 100rpx;margin-right: 100rpx">
						<u-form ref="uForm">
							<u-form-item label="头像">
								<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"
									slot="right">
									<image class="avatar" :src="user.avatarUrl"></image>
								</button>
							</u-form-item>
							<u-form-item label="昵称">
								<input type="nickname" @blur="updateUserName" v-model="user.nickName" class="weui-input"
									placeholder="请输入昵称" />
							</u-form-item>
						</u-form>
					</div>
				</div>
				<div class="auth-btncard">
					<div class="btn-unok"><u-button :hair-line='false' :custom-style="customStyleUnOk" @click="logout">
							拒绝</u-button></div>
					<div class="btn-ok"><u-button type="primary" :hair-line='false' :custom-style="customStyleOk"
							@click="authUser"> 允许</u-button></div>
				</div>
			</view>
		</u-modal>
	</view>
</template>


<script>
	import sendVerifyCode from "@/mixins/SendVerifyCode";
	import Routine from '@/libs/routine';
	import {
		getRand,
		getRandom
	} from '@/api/common';
	import {
		xcxLogin,
		saveType,
		updateUserInfo
	} from '@/api/user';
	import {
		auth
	} from '@/api/wechat';
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';
	export default {
		data() {
			return {
				user: {
					userId: null,
					avatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
					nickName: '',
				},
				current: 0,
				tabNav: ['验证码登录', '手机号登录'],
				showUpImg: true,
				isShow: true,
				showAuthorizeUser: false,
				isAgree: false,
				keyLock: true,
				account: "",
				password: "",
				captcha: "",
				random: "",
			}
		},

		mixins: [sendVerifyCode],

		onLoad() {

		},

		onShow() {

		},

		methods: {
			authUser() {
				let that = this;
				//判断是否补全资料
				if (this.user.avatarUrl == null || this.user.avatarUrl ==
					'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0' ||
					this.user.nickName == null || this.user.nickName == '') {
					that.$util.Tips({
						title: `请补全个人信息`,
						icon: 'error'
					});
				} else {
					that.$util.Tips({
						title: `登录成功`,
						icon: 'success'
					}, {
						tab: 3,
						url: 2
					});
				}
			},
			logout() {
				let that = this;
				that.$store.commit("LOGOUT");
				uni.reLaunch({
					url: '/pages/user/index',
				})
			},
			updateUserName() {
				updateUserInfo({
					userInfoId: this.user.userId,
					userName: this.user.nickName
				}).then(res => {

				}).catch(err => {
					that.$util.Tips({
						title: '失败'
					})
				})
			},
			onChooseAvatar(e) {
				let that = this;
				const {
					avatarUrl
				} = e.detail
				this.user.avatarUrl = avatarUrl
				uni.uploadFile({
					url: HTTP_REQUEST_URL + '/api/' + 'user/updateHeadImage',
					filePath: avatarUrl,
					name: 'headImageFiles',
					formData: {
						'userInfoId': this.user.userId
					},
					header: {
						// #ifdef MP
						"Content-Type": "multipart/form-data",
						// #endif
					},
					success: function(res) {
						uni.hideLoading();
						let data = res.data ? JSON.parse(res.data) : {};
						console.log(data);
					},
					fail: function(res) {
						uni.hideLoading();
						that.Tips({
							title: '上传图片失败'
						});
					}
				})
			},

			changePwd: function() {
				this.isShow = !this.isShow;
				this.showUpImg = !this.showUpImg
			},

			/**
			 * @param {Object} code
			 * 获取openid
			 */
			getAuth(code) {
				return new Promise((resolve, reject) => {
					let that = this;
					auth({
						wxCode: code
					}).then(res => {
						resolve(res.value);
					}).catch(err => {
						reject(err)
					})
				});
			},

			/**
			 * 手机登录
			 */
			loginMobile() {
				let that = this;
				if (!that.account) return that.$util.Tips({
					title: '请输入手机号码'
				});
				if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
					title: '请输入正确的手机号码'
				});
				if (!that.current) {
					if (!that.captcha) return that.$util.Tips({
						title: '请填写验证码'
					});
					if (!/^[\w\d]+$/i.test(that.captcha)) return that.$util.Tips({
						title: '请输入正确的验证码'
					});
				} else {
					if (!that.password) return that.$util.Tips({
						title: '请输入密码'
					});
				}

				if (!that.isAgree) return that.$util.Tips({
					title: '请勾选用户协议与隐私政策'
				});
				if (this.keyLock) {
					this.keyLock = !this.keyLock
				} else {
					return that.$util.Tips({
						title: '请勿重复点击'
					});
				}

				let data = {};
				if (!that.current) {
					data = {
						userPhone: that.account,
						randCode: that.captcha,
						unionId: '',
						xcxOpenId: ''
					};
				} else {
					data = {
						userPhone: that.account,
						passWord: that.password,
						unionId: '',
						xcxOpenId: ''
					};
				}
				Routine.getCode().then(code => {
					that.getAuth(code).then(res => {
						data.unionId = res.unionid;
						data.openId = res.openId;
						xcxLogin(data).then(res => {
							this.keyLock = true
							let data = res.value;
							this.user.userId = res.value.userInfoId;
							that.$store.commit("LOGIN", {
								'token': data.token,
								'uid': data.userInfoId,
								// 'time': data.expires_time - this.$Cache.time()
							});
							that.$store.commit("SETUID", res.value.userInfoId);
							that.$store.commit("USER_TYPE", res.value.userType);
							that.$store.commit("UPDATE_USERINFO", res.value);
							// if (res.value.userType) {
							// 	that.$util.Tips({
							// 		title: `登录成功`,
							// 		icon: 'success'
							// 	}, {
							// 		tab: 1,
							// 		url: '/pages/user/index'
							// 	});
							// } else {
							// 	that.$util.Tips({
							// 		title: `登录成功`,
							// 		icon: 'success'
							// 	}, {
							// 		tab: 5,
							// 		url: '/pages/users/user_role/index'
							// 	});
							// }

							if (!res.value.userType) {
								saveType({
									userInfoId: res.value.userInfoId,
									userType: 'STORE'
								}).then(res => {
									that.$store.commit('USER_TYPE', 'STORE');
								}).catch(err => {
									that.$util.Tips({
										title: err
									})
								})
							}

							//判断用户的头像和昵称是否补齐
							if (res.value.headImgUrl == null || res.value.headImgUrl == '' || res
								.value.userName == null || res.value.userName == '') {
								uni.hideLoading();
								this.showAuthorizeUser = true;
							} else {
								that.$util.Tips({
									title: `登录成功`,
									icon: 'success'
								}, {
									tab: 1,
									url: '/pages/index/index'
								});
							}


						}).catch(err => {
							uni.hideLoading();
							this.keyLock = true
							that.$util.Tips({
								title: err
							});
						})
					})
				})

			},


			/**
			 * 获取验证码
			 * 先获取随机码去校验才能得到验证码
			 */
			async getCode() {
				let that = this;
				if (!that.account) return that.$util.Tips({
					title: '请输入手机号码'
				});
				if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
					title: '请输入正确的手机号码'
				});
				/**
				 * 获取随机数
				 */
				await that.getRandom(that.account);
				/**
				 * 发送验证码
				 */
				await getRand({
					userPhone: that.account,
					randType: 'USER_LOGIN',
					randomCode: that.random
				}).then(res => {
					that.$util.Tips({
						title: '发送成功'
					});
					that.sendCode();
				}).catch(err => {
					that.$util.Tips({
						title: err
					});
				})
			},

			/**
			 * 获取随机码
			 */
			async getRandom(account) {
				let that = this;
				await getRandom({
					userPhone: account,
				}).then(res => {
					that.random = that.handleRandom(res.value);
					console.log(that.random);
				}).catch(err => {
					that.$util.Tips({
						title: err
					});
				});
			},

			/**
			 * 处理随机码
			 * 取随机码的第1/5/9/13四个字符
			 */
			handleRandom(code) {
				let str = '';
				str += code.substr(0, 1);
				str += code.substr(4, 1);
				str += code.substr(8, 1);
				str += code.substr(12, 1);
				return str;
			},

			goUrl(url) {
				let that = this;
				that.$util.Tips(url);
			}
		}
	}
</script>

<style>
	.container .tab {
		padding: 30rpx;
	}

	.container .tab text {
		font-size: 40rpx;
		margin-right: 40rpx;
		vertical-align: middle;
	}

	.container .tab text.on {
		font-weight: bold;
		font-size: 48rpx;
	}

	.uni-list::before,
	.uni-list::after {
		display: none;
	}

	.container .bd .uni-flex {
		color: #06A972;
	}

	.container .bd image {
		width: 24rpx;
		height: 24rpx;
	}

	.container .p {
		font-size: 24rpx;
		margin-bottom: 40rpx;
	}

	.container .p .checkbox {
		transform: scale(0.7);
		color: #06A972;
	}

	/* .container .p text {
		color: #06A972;
	} */

	.container .bd .uni-list-cell-left {
		padding-left: 0;
	}

	.container .bd .yzm {
		color: #06A972;
		font-size: 28rpx;
		background: transparent;
	}

	.container .bd button::after {
		border: none;
	}

	.container .ft {
		padding: 60rpx 60rpx 0;
	}

	.justify {
		width: 80rpx;
		height: 40rpx;
		line-height: 40rpx;
		text-align: justify;
		text-align-last: justify;
		text-justify: inter-ideograph;
	}
</style>
<style lang="scss" scoped>
	.auth-btncard {
		.btn-unok {
			width: 50%;
			float: left;
		}

		.btn-ok {
			width: 50%;
			float: left;
			margin: 0;
			padding: 0;
			border: 0px solid transparent;
			outline: none;

			u-button {
				margin: 0;
				padding: 0;
				border: 0px solid transparent;
				outline: none;
			}
		}
	}

	.auth-card {
		text-align: center;

		.avatar-img {
			width: 150rpx;
			height: 150rpx;
			overflow: hidden;
			border-radius: 100%;
			margin-top: 30rpx;
		}

		.title {
			font-size: 20rpx;
		}

		.content {
			margin-top: 10rpx;
		}
	}

	.authorize-box {
		background-color: transparent;
		text-align: center;

		.authorize-avatar {
			width: 200rpx;
			height: 200rpx;
		}

		.authorize-btn {
			position: relative;
			top: 40rpx;
		}
	}

	.u-mode-center-box {
		background-color: transparent !important;
	}

	.avatar-wrapper {
		width: 150rpx;
		height: 100rpx;
		color: #333 !important;
		text-align: center !important;
		border: none !important;
		border-radius: 0 !important;
		background-color: transparent !important;
	}

	.avatar-wrapper::after {
		border: none !important;
	}

	.avatar {
		width: 100rpx;
		height: 100rpx;
		overflow: hidden;
		border-radius: 100%;
	}
</style>